import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

export default class CameraController {
    constructor(camera, renderer) {
        this.camera = camera;
        this.controls = new OrbitControls(camera, renderer.domElement);
        this.setupControls();
        
        // 跟随车辆的设置
        this.followCar = true;
        this.isMouseControlling = false;
        this.cameraOffset = new THREE.Vector3(0, 5, 10); // 相机相对于小车的偏移量
        
        // 添加鼠标事件监听
        this.setupEventListeners();
    }
    
    setupControls() {
        this.controls.enableDamping = true;
        this.controls.dampingFactor = 0.1;
        this.controls.target.set(0, 1, 0);
        this.controls.maxPolarAngle = Math.PI / 2 - 0.05;
        this.controls.minDistance = 5;
        this.controls.maxDistance = 50;
    }
    
    setupEventListeners() {
        document.addEventListener('mousedown', () => {
            this.isMouseControlling = true;
            this.followCar = false;
        }, false);

        document.addEventListener('mouseup', () => {
            this.isMouseControlling = false;
            this.followCar = true;
        }, false);
        
        // 窗口大小调整事件
        window.addEventListener('resize', () => {
            this.camera.aspect = window.innerWidth / window.innerHeight;
            this.camera.updateProjectionMatrix();
        }, false);
    }
    
    update(chassisBody) {
        if (this.followCar && !this.isMouseControlling && chassisBody) {
            // 计算相机目标位置（跟随小车）
            const carPosition = new THREE.Vector3().copy(chassisBody.position);
            
            // 获取小车的方向向量（基于四元数）
            const carDirection = new THREE.Vector3(0, 0, 1).applyQuaternion(chassisBody.quaternion);
            
            // 计算相机位置（在小车后方和上方）
            const cameraPosition = carPosition.clone().add(
                this.cameraOffset.clone().applyQuaternion(chassisBody.quaternion)
            );
            
            // 平滑过渡到新位置
            this.camera.position.lerp(cameraPosition, 0.05);
            
            // 设置相机看向小车
            this.controls.target.lerp(carPosition, 0.05);
        }
        
        this.controls.update(); // 更新 OrbitControls
    }
}